/**
 * Classname :DateConverter.java
 */
package com.astrocsr.common.convertor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.util.StrutsTypeConverter;

import com.astrocsr.common.util.DateUtil;

public class DateConverter extends StrutsTypeConverter {
	static final Logger log = Logger.getLogger(DateConverter.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
		Date result = null; 
		if (arg1 != null && arg1.length > 0 && StringUtils.isNotBlank(arg1[0])) {
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.LOCAL_SLASH_SHORTYEAR);
			try {
				result = sdf.parse(arg1[0]);
			} catch (ParseException e) {				
				try {
					// TODO: handle exception
					log.info("Can not parse [" + arg1[0] + "] to Date with format " + DateUtil.LOCAL_SLASH_SHORTYEAR);
					sdf = new SimpleDateFormat(DateUtil.LOCAL_SLASH);
					result = sdf.parse(arg1[0]);
				} catch (Exception e2) {
					// TODO: handle exception
					try {
						log.info("Can not parse [" + arg1[0] + "] to Date with format " + DateUtil.LOCAL_SLASH);
					} catch (Exception pe) {					
						log.error("Error converting value [" + arg1[0] + "] to Date ", pe);
					}
				}
			}   
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String convertToString(Map arg0, Object arg1) {
		if (arg1 instanceof Date) {
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.LOCAL_SLASH_SHORTYEAR);
			return sdf.format((Date) arg1);
		}
		return "";
	}
}
